﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace BlueFox.Ucpaas
{
    public class HttpUtil
    {
        internal static string Sid { get; set; }
        internal static string Token { get; set; }
        internal static string Appid { get; set; }

        public static string PostJson(string url, JObject data)
        {
            HttpWebRequest request = GetPostHttpConn(url);
            byte[] requestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
            request.ContentLength = requestData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestData, 0, requestData.Length);
            requestStream.Close();

            // 接收返回包
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string responseStr = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            if (HttpStatusCode.OK == response.StatusCode)
            {
                return responseStr;
            }
            else
            {
                return responseStr;
            }
        }

        public static HttpWebRequest GetPostHttpConn(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Accept = "application/json";
            return request;
        }

        public static void SetConfig(string sid,string token,string appid)
        {
            Sid = sid;
            Token = token;
            Appid = appid;
        }
    }
}
